import fs from 'fs';
import path from 'path';
import url from 'url';

import { adminRouter } from '../../src/routes/router.config';
import { FeAuthType, adminPrefix, ignorePath } from './config';
import { findDeps, getDeptsApi, resolvePath } from './util';

const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 1. 标记公共接口, 比如store/api
// 2. 遍历目录
// 3. ast解析文件
// 4. 找到文件关联的api
// 5. 生成json文件

// 遍历目录
function traverseDir(routeList: RouteData[], parentPath = '/') {
  const result: BASE.SyncPageAndApiDTO[] = [];

  routeList.forEach((route) => {
    const element = route.element?.toString().match(/\((["']?)([^"')]+)\1\)/)?.[2];

    // 如果是 layout 组件，则忽略当前节点，把 children 提到上一级
    if (element === '@/layouts/basic') {
      if (route.children) {
        const childrenResult = traverseDir(route.children, route.path);
        result.push(...childrenResult);
      }

      return;
    }

    const item: BASE.SyncPageAndApiDTO = {
      permissionName: route.name || route.path || (route.element as string),
      type: FeAuthType.菜单
    } as BASE.SyncPageAndApiDTO;

    if (route.path) {
      const path = `${parentPath}${route.path}`;
      item.permissionCode = `admin:${path}`;
    }

    // 查找当前路由的依赖树, 并找到请求的api
    if (typeof element === 'string' && route.path) {
      process.stdout.clearLine(0); // 清除上一行
      process.stdout.cursorTo(0); // 光标移到行首
      process.stdout.write(`\r当前进度: ${route.name || route.path || route.element}`);

      const src = resolvePath(element);

      if (src) {
        const normalize = src.replace(/\\/g, '/');

        if (ignorePath.some((reg) => reg.test(normalize))) {
          return;
        }

        const depsTree = findDeps(src);
        // console.dir(depsTree, { depth: null })
        const api = getDeptsApi(depsTree);
        item.apiList = api.map((api) => `${api.method}:${api.url}`);
      }
    }

    if (route.children) {
      item.child = traverseDir(
        route.children,
        route.path ? `${parentPath}${route.path}/` : parentPath
      );
    }

    result.push(item);
  });

  return result;
}

const adminRouterConfig = traverseDir(adminRouter);
const config: BASE.SyncPageAndApiDTO[] = [
  {
    permissionName: '后台管理系统',
    permissionCode: adminPrefix,
    type: FeAuthType.端,
    child: adminRouterConfig
  }
];

// 当前目录保存文件
const json = JSON.stringify(config, null, 2);
const filePath = path.join(__dirname, './router.json');
fs.writeFileSync(filePath, json);
